package com.example.ffepeg.ffeAdder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

//视频配音与字幕
public class VideoToSubtitles {
    //https://pushimg.liecaizhijia.com/ai_conflate/video2024-12-23/b1ac1158-8658-4819-85e8-a178024d2eb0.mp4   6秒的视频

    public static void main(String[] args) {
        String videoFile  = "https://pushimg.liecaizhijia.com/ai_conflate/video2024-12-17/42bd8270-9abe-4197-b359-d424b9047671.mp4";
        String subtitleFile  = "src/main/resources/file/31734595312920file.srt";
        String wavPath = "src/main/resources/file/a3a76acc-96c9-4137-8880-db06118fd2bd.wav";
        String outputFile  = "src/main/resources/out/outSubtitle.mp4";

        String musPath = "src/main/resources/file/9716c9doutput.mp3";
        String outMusic = "src/main/resources/out/outMusicFiles.mp4";

       //mergeVideoAudioSubtitle(videoFile, wavPath, subtitleFile, outputFile);


        mergeVideoAudioSubtitle(
                videoFile,
                "src/main/resources/file/filespath/06fb892b-f7b6-4de1-b584-97a6ab971f67.wav",
                "src/main/resources/file/filespath/900147480a2f4565a1b17b3c35f093971735111205120file.srt",
                "src/main/resources/out/out31205ileAAAA.mp4"
        );

       /* mergeVideoAudioBase(
                "src/main/resources/out/out31205ileAAAA.mp4",
                "D:\\javaXM\\FFEpeg\\src\\main\\resources\\file\\videoThen\\holahsdlfjlasdjfads.mp3",
                "D:\\javaXM\\FFEpeg\\src\\main\\resources\\out\\outMusicFiles.mp4");*/

        //获取时长
//        Integer i = videoTime(videoFile);
//        System.out.println(i);

    }
    //给视频添加音频与字幕
    public static boolean mergeVideoAudioSubtitle(String videoPath, String audioPath, String subtitlePath, String outputPath) {
        try {
          /* ProcessBuilder builder = new ProcessBuilder(
                    "ffmpeg",
                    "-i",videoPath,
                    "-i",audioPath,
                    "-vf","subtitles="+subtitlePath,
                    "-c:v","libx264",
                    "-c:a","aac",
                    "-threads", "2",
                    outputPath
            );*/
            ProcessBuilder builder = new ProcessBuilder(
                    "ffmpeg",
                    "-i",videoPath,
                    "-i",audioPath,
                    "-vf","subtitles="+subtitlePath + ",scale=iw:ih",
                    "-c:v","libx264",
                    "-crf", "18",
                    "-preset", "slow",
                    "-c:a","aac",
                    "-b:a", "192k",
                    "-threads", "2",
                    outputPath
            );

            builder.redirectErrorStream(true);
            Process process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int code = process.waitFor();
            System.out.println("数据为: "+ code);
            if (code == 0){
                return true;
            }else {
                throw new RuntimeException("视频生成失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    //为视频添加字幕
    public static void addZimuDate(String video,String subtitlePath, String outputPath){
        ProcessBuilder builder = new ProcessBuilder(
                "ffmpeg", "-i", video, "-vf", "subtitles=" + subtitlePath, outputPath
        );
        try {
            builder.redirectErrorStream(true);
            Process process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            System.out.println("FFmpeg finished with exit code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    //添加背景音乐
    public static void mergeVideoAudioBase(String video,String musPath, String outMusic){
       /* ProcessBuilder builder = new ProcessBuilder(
                "ffmpeg", "-i", video, "-stream_loop", "-1", "-i", musPath,
                "-filter_complex", "[0:a][1:a]amix=inputs=2:duration=first:dropout_transition=3",
                "-c:v", "copy", "-c:a", "aac", outMusic
        );*/
        ProcessBuilder builder = new ProcessBuilder(
                "ffmpeg", "-i", video, "-stream_loop", "-1", "-i", musPath, "-filter_complex",
                "[1:a]apad,aresample=44100[a];[0:a][a]amix=inputs=2:duration=shortest[aout]",
                "-map", "0:v", "-map", "[aout]",
                "-c:v", "copy", "-c:a", "aac", outMusic
        );
        try {
            builder.redirectErrorStream(true);
            Process process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            System.out.println("FFmpeg finished with exit code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static Integer videoTime(String videoPath){
        try {
            Process process = Runtime.getRuntime().exec(
                    "ffprobe -i " + videoPath+ " -show_entries format=duration -v quiet -of csv=\"p=0\" -threads 2"
            );
            // 读取输出
            int time = 0;
            try (Scanner scanner = new Scanner(process.getInputStream()).useDelimiter("\\A")) {
                if (scanner.hasNext()) {
                    String durationStr = scanner.next().trim();
                    double duration = Double.parseDouble(durationStr);
                    time = (int) duration;
                }
            }catch (Exception e){
                throw new RuntimeException("获取视频时长失败");
            }
            return time;
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
}
